import pygame
import sys
import os
import traceback
from pygame.locals import *
from random import choice

import EnemyPlane
import MyPlane
import Bullet
import Supply

pygame.init()
pygame.mixer.init()
# 背景尺寸
bg_size = width, height = 480, 700
screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("飞机大战")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 获取当前项目的路径
projectPath = os.path.abspath('..')

# 背景图片
background = pygame.image.load(projectPath + "/resources/images/background.png").convert()

# 载入音乐
pygame.mixer.music.load(projectPath + '/resources/sound/hundouluo.wav')
pygame.mixer.music.set_volume(0.2)

bullet_sound = pygame.mixer.Sound(projectPath + '/resources/sound/bullet.wav')
bullet_sound.set_volume(0.2)

bomb_sound = pygame.mixer.Sound(projectPath + '/resources/sound/use_bomb.wav')
bomb_sound.set_volume(0.2)

supply_sound = pygame.mixer.Sound(projectPath + '/resources/sound/supply.wav')
supply_sound.set_volume(0.2)

get_bomb_sound = pygame.mixer.Sound(projectPath + '/resources/sound/get_bomb.wav')
get_bomb_sound.set_volume(0.2)

get_bullet_sound = pygame.mixer.Sound(projectPath + '/resources/sound/get_bullet.wav')
get_bullet_sound.set_volume(0.2)

upgrade_sound = pygame.mixer.Sound(projectPath + '/resources/sound/upgrade.wav')
upgrade_sound.set_volume(0.2)

enemy3_fly_sound = pygame.mixer.Sound(projectPath + '/resources/sound/enemy3_flying.wav')
enemy3_fly_sound.set_volume(0.6)

enemy1_down_sound = pygame.mixer.Sound(projectPath + '/resources/sound/enemy1_down.wav')
enemy1_down_sound.set_volume(0.2)

enemy2_down_sound = pygame.mixer.Sound(projectPath + '/resources/sound/enemy2_down.wav')
enemy2_down_sound.set_volume(0.2)

enemy3_down_sound = pygame.mixer.Sound(projectPath + '/resources/sound/enemy3_down.wav')
enemy3_down_sound.set_volume(0.2)

me_down_sound = pygame.mixer.Sound(projectPath + '/resources/sound/me_down.wav')
me_down_sound.set_volume(0.2)


def addSmallEnemyPlanes(group1, group2, num):
    for i in range(num):
        enemyPlane = EnemyPlane.SmallEnemyPlane(bg_size)
        group1.append(enemyPlane)
        group2.append(enemyPlane)


def addMediumEnemyPlanes(group1, group2, num):
    for i in range(num):
        enemyPlane = EnemyPlane.MediumEnemyPlane(bg_size)
        group1.append(enemyPlane)
        group2.append(enemyPlane)


def addBigEnemyPlanes(group1, group2, num):
    for i in range(num):
        enemyPlane = EnemyPlane.BigEnemyPlane(bg_size)
        group1.append(enemyPlane)
        group2.append(enemyPlane)


def inc_speed(target, inc):
    for plane in target:
        plane.speed += inc


def main():
    # 播放音乐
    pygame.mixer.music.play(-1)

    # 创建我方飞机
    myPlane = MyPlane.MyPlane(bg_size)

    # 用于切换飞机图片的变量
    switchImage = True
    # 用于延时图片切换
    delaySwitchImage = 100

    # 统计得分的变量
    score = 0
    score_font = pygame.font.Font(projectPath + "/resources/font/font.ttf", 24)

    # 标志是否暂停游戏
    paused = False
    pause_nor_image = pygame.image.load(projectPath + "/resources/images/pause_nor.png").convert_alpha()
    pause_pressed_image = pygame.image.load(projectPath + "/resources/images/pause_pressed.png").convert_alpha()
    resume_nor_image = pygame.image.load(projectPath + "/resources/images/resume_nor.png").convert_alpha()
    resume_pressed_image = pygame.image.load(projectPath + "/resources/images/resume_pressed.png").convert_alpha()

    paused_rect = pause_nor_image.get_rect()
    paused_rect.left = width - paused_rect.width - 10
    paused_rect.top = 10
    # 默认显示
    paused_image = pause_nor_image

    # 设置游戏难度级别
    level = 1

    # 设置全屏炸弹
    bomb_image = pygame.image.load(projectPath + "/resources/images/bomb.png").convert_alpha()
    bomb_rect = bomb_image.get_rect()
    bomb_font = pygame.font.Font(projectPath + "/resources/font/font.ttf", 48)
    bomb_num = 3

    # 每30秒发放一个补给包，分别是炸弹和超级子弹
    bulletSupply = Supply.BulletSupply(bg_size)
    bombSupply = Supply.BombSupply(bg_size)
    SUPPLY_TIME = USEREVENT
    pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)

    # 生成敌方飞机
    enemyPlanes = []

    # 生成敌方小型飞机
    smallEnemyPlanes = []
    addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 15)

    # 生成敌方中型飞机 pygame.sprite.Group()
    mediumEnemyPlanes = []
    addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 4)

    # 生成敌方大型飞机
    bigEnemyPlanes = []
    addBigEnemyPlanes(bigEnemyPlanes, enemyPlanes, 2)

    # 生成子弹
    bullets = []

    # 生成超级子弹
    superBullets = []
    # 超级子弹定时器
    SUPER_BULLET_TIME = USEREVENT + 1
    # 标志是否使用超级子弹
    isSuperBullet = False
    # 不会停下的超级子弹
    isSuperBulletNotStop = False

    # 真正发射的子弹
    really_bullets = []

    # 我方飞机生命数量
    life_image = pygame.image.load(projectPath + "/resources/images/life.png").convert_alpha()
    life_rect = life_image.get_rect()
    life_num = 3
    # 设置是否处于无敌(不会死)状态
    isNotDead = False
    # 复活时无敌的计时器
    IS_NOT_DEAD_TIME = USEREVENT + 2

    # 被击中后的图片索引
    enemy1_destroy_index = 0
    enemy2_destroy_index = 0
    enemy3_destroy_index = 0
    me_destroy_index = 0

    # 用于阻止重复打开记录文件
    recorded = False

    # 游戏结束画面
    gameover_font = pygame.font.Font(projectPath + "/resources/font/font.TTF", 48)
    again_image = pygame.image.load(projectPath + "/resources/images/again.png").convert_alpha()
    again_rect = again_image.get_rect()
    gameover_image = pygame.image.load(projectPath + "/resources/images/gameover.png").convert_alpha()
    gameover_rect = gameover_image.get_rect()

    clock = pygame.time.Clock()
    running = True

    while running:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1 and paused_rect.collidepoint(event.pos):
                    paused = not paused
                    if paused:
                        pygame.time.set_timer(SUPPLY_TIME, 0)
                        pygame.mixer.music.pause()
                        pygame.mixer.pause()
                    else:
                        pygame.time.set_timer(SUPPLY_TIME, 30 * 1000)
                        pygame.mixer.music.unpause()
                        pygame.mixer.unpause()

            elif event.type == MOUSEMOTION:
                if paused_rect.collidepoint(event.pos):
                    if paused:
                        paused_image = resume_pressed_image
                    else:
                        paused_image = pause_pressed_image
                else:
                    if paused:
                        paused_image = resume_nor_image
                    else:
                        paused_image = pause_nor_image

            elif event.type == KEYDOWN:
                if event.key == K_SPACE:
                    if bomb_num:
                        bomb_num -= 1
                        bomb_sound.play()
                        # 所有在屏幕中的飞机
                        for plane in enemyPlanes:
                            if plane.rect.bottom > 0:
                                plane.active = False
                # 自己加的外挂，按a键发射超级子弹或取消超级子弹
                elif event.key == K_c:
                    isSuperBulletNotStop = not isSuperBulletNotStop
                # 外挂,释放全屏炸弹
                elif event.key == K_v:
                    bomb_sound.play()
                    # 所有在屏幕中的飞机
                    for plane in enemyPlanes:
                        if plane.rect.bottom > 0:
                            plane.active = False
                elif event.key == K_n:
                    isNotDead = not isNotDead
                    if isNotDead:
                        myPlane.active = True

            elif event.type == SUPPLY_TIME:
                supply_sound.play()
                if choice([True, False]):
                    bulletSupply.reset()
                else:
                    bombSupply.reset()

            elif event.type == SUPER_BULLET_TIME:
                isSuperBullet = False
                pygame.time.set_timer(SUPER_BULLET_TIME, 0)

            elif event.type == IS_NOT_DEAD_TIME:
                isNotDead = False
                pygame.time.set_timer(IS_NOT_DEAD_TIME, 0)

        # 背景图片
        screen.blit(background, (0, 0))

        # 根据用户得分增加游戏难度
        if level == 1 and score > 5000:
            level = 2
            # 难度提升音效
            upgrade_sound.play()
            # 增加敌机
            addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 5)
            addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 2)

            # 提升小型敌机速度
            inc_speed(smallEnemyPlanes, 1)
        elif level == 2 and score > 20000:
            level = 3
            # 难度提升音效
            upgrade_sound.play()
            # 增加敌机
            addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 5)
            addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 3)
            addBigEnemyPlanes(bigEnemyPlanes, enemyPlanes, 1)
            # 提升小型敌机和中型敌机速度
            inc_speed(smallEnemyPlanes, 1)
            inc_speed(mediumEnemyPlanes, 1)
        elif level == 3 and score > 100000:
            level = 4
            # 难度提升音效
            upgrade_sound.play()
            # 增加敌机
            addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 5)
            addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 3)
            # 提升小型敌机和中型敌机速度
            inc_speed(smallEnemyPlanes, 1)
        elif level == 4 and score > 500000:
            level = 5
            # 难度提升音效
            upgrade_sound.play()
            # 增加敌机
            addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 10)
            addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 5)
            addBigEnemyPlanes(bigEnemyPlanes, enemyPlanes, 3)
            # 提升小型敌机和中型敌机速度
            inc_speed(smallEnemyPlanes, 1)
            inc_speed(mediumEnemyPlanes, 1)
        elif level == 5 and score > 1000000:
            level = 6
            # 难度提升音效
            upgrade_sound.play()
            # 增加敌机
            addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 20)
            addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 10)
            addBigEnemyPlanes(bigEnemyPlanes, enemyPlanes, 5)
            # 提升小型敌机和中型敌机速度
            inc_speed(smallEnemyPlanes, 1)
            inc_speed(mediumEnemyPlanes, 1)
            inc_speed(bigEnemyPlanes, 1)
        elif level == 6 and score > 2000000:
            level = 7
            # 难度提升音效
            upgrade_sound.play()
            # 增加敌机
            addSmallEnemyPlanes(smallEnemyPlanes, enemyPlanes, 10)
            addMediumEnemyPlanes(mediumEnemyPlanes, enemyPlanes, 5)
            addBigEnemyPlanes(bigEnemyPlanes, enemyPlanes, 2)
            # 提升小型敌机和中型敌机速度
            inc_speed(smallEnemyPlanes, 1)
            inc_speed(mediumEnemyPlanes, 1)
            inc_speed(bigEnemyPlanes, 1)

        # 如果没有暂停
        if not paused and life_num:

            # 检测用户的键盘操作
            keyPressed = pygame.key.get_pressed()

            # 我方飞机上下左右移动
            if keyPressed[K_w] or keyPressed[K_UP]:
                myPlane.moveUp()
            if keyPressed[K_s] or keyPressed[K_DOWN]:
                myPlane.moveDown()
            if keyPressed[K_a] or keyPressed[K_LEFT]:
                myPlane.moveLeft()
            if keyPressed[K_d] or keyPressed[K_RIGHT]:
                myPlane.moveRight()

            # 绘制炸弹补给并检测是否获得
            if bombSupply.active:
                bombSupply.move()
                screen.blit(bombSupply.image, bombSupply.rect)
                if pygame.sprite.collide_mask(bombSupply, myPlane):
                    get_bomb_sound.play()
                    bomb_num += 1
                    bombSupply.active = False

            # 绘制超级子弹补给并检测是否获得
            if bulletSupply.active:
                bulletSupply.move()
                screen.blit(bulletSupply.image, bulletSupply.rect)
                if pygame.sprite.collide_mask(bulletSupply, myPlane):
                    get_bullet_sound.play()
                    # 发射超级子弹
                    isSuperBullet = True
                    pygame.time.set_timer(SUPER_BULLET_TIME, 30 * 1000)
                    bulletSupply.active = False

            # 切换图片
            if not (delaySwitchImage % 5):
                switchImage = not switchImage

            delaySwitchImage -= 1
            if delaySwitchImage == 0:
                delaySwitchImage = 100

            # 发射子弹
            if not (delaySwitchImage % 5):
                bullet_sound.play()
                if isSuperBulletNotStop or isSuperBullet:
                    # 同时射五发
                    superBullets.append(Bullet.SuperBullet(myPlane.rect.midtop))
                    superBullets.append(Bullet.SuperBullet((myPlane.rect.centerx - 33, myPlane.rect.centery)))
                    superBullets.append(Bullet.SuperBullet((myPlane.rect.centerx - 58, myPlane.rect.centery)))
                    superBullets.append(Bullet.SuperBullet((myPlane.rect.centerx + 30, myPlane.rect.centery)))
                    superBullets.append(Bullet.SuperBullet((myPlane.rect.centerx + 55, myPlane.rect.centery)))
                    really_bullets = superBullets
                else:
                    bullets.append(Bullet.Bullet(myPlane.rect.midtop))
                    really_bullets = bullets

            # 检测我方飞机是否被撞
            enemies_down = pygame.sprite.spritecollide(myPlane, enemyPlanes, False, pygame.sprite.collide_mask)
            if enemies_down:
                if not isNotDead:
                    myPlane.active = False
                for e in enemies_down:
                    e.active = False

            # 绘制我方飞机
            if myPlane.active:
                if switchImage:
                    screen.blit(myPlane.image1, myPlane.rect)
                else:
                    screen.blit(myPlane.image2, myPlane.rect)
            else:  # 被摧毁
                if not (delaySwitchImage % 3):
                    if me_destroy_index == 0:
                        me_down_sound.play()
                    screen.blit(myPlane.destroyImages[me_destroy_index], myPlane.rect)
                    me_destroy_index = (me_destroy_index + 1) % 4
                    if me_destroy_index == 0:
                        if isNotDead:
                            myPlane.revive()
                        elif life_num:
                            myPlane.revive()
                            isNotDead = True
                            pygame.time.set_timer(IS_NOT_DEAD_TIME, 3 * 1000)
                            life_num -= 1

            # 检测子弹是否击中敌机
            for bullet in really_bullets:
                if bullet.active:
                    bullet.move()
                    screen.blit(bullet.image, bullet.rect)
                    enemyHit = pygame.sprite.spritecollide(bullet, enemyPlanes, False, pygame.sprite.collide_mask)
                    if enemyHit:
                        bullet.active = False
                        for enemy in enemyHit:
                            if enemy in mediumEnemyPlanes or enemy in bigEnemyPlanes:
                                enemy.hit = True
                                enemy.energy -= 1
                                if enemy.energy == 0:
                                    enemy.active = False
                            else:
                                enemy.active = False

            # 删除已经消亡的子弹，即active=False
            for bullet in really_bullets:
                if not bullet.active:
                    really_bullets.remove(bullet)

            # 绘制大型敌方飞机
            for plane in bigEnemyPlanes:
                if plane.active:
                    plane.move()
                    if plane.hit:
                        # 绘制被击中的画面
                        screen.blit(plane.imageHit, plane.rect)
                        plane.hit = False
                    else:
                        if switchImage:
                            screen.blit(plane.image1, plane.rect)
                        else:
                            screen.blit(plane.image2, plane.rect)

                    # 绘制血槽
                    pygame.draw.line(screen, BLACK, (plane.rect.left, plane.rect.top - 5),
                                     (plane.rect.right, plane.rect.top - 5), 2)
                    # 当生命大于20%显示绿色，否则显示红色
                    energy_remain = plane.energy / EnemyPlane.BigEnemyPlane.energy
                    if energy_remain > 0.2:
                        energy_color = GREEN
                    else:
                        energy_color = RED
                    pygame.draw.line(screen, energy_color, (plane.rect.left, plane.rect.top - 5),
                                     (plane.rect.left + int(plane.rect.width * energy_remain), plane.rect.top - 5), 2)

                    # 大型机即将出现，播放音效
                    if plane.rect.bottom > -50:
                        enemy3_fly_sound.play(-1)
                else:  # 被摧毁
                    if not (delaySwitchImage % 3):
                        if enemy3_destroy_index == 0:
                            enemy3_down_sound.play()
                        screen.blit(plane.destroyImages[enemy3_destroy_index], plane.rect)
                        enemy3_destroy_index = (enemy3_destroy_index + 1) % 6
                        if enemy3_destroy_index == 0:
                            enemy3_fly_sound.stop()
                            # 一辆大型敌机2000分
                            score += 10000
                            plane.reset()

            # 绘制中型敌方飞机
            for plane in mediumEnemyPlanes:
                if plane.active:
                    plane.move()
                    if plane.hit:
                        # 绘制被击中的画面
                        screen.blit(plane.imageHit, plane.rect)
                        plane.hit = False
                    else:
                        screen.blit(plane.image, plane.rect)

                    # 绘制血槽
                    pygame.draw.line(screen, BLACK, (plane.rect.left, plane.rect.top - 5),
                                     (plane.rect.right, plane.rect.top - 5), 2)
                    # 当生命大于20%显示绿色，否则显示红色
                    energy_remain = plane.energy / EnemyPlane.MediumEnemyPlane.energy
                    if energy_remain > 0.2:
                        energy_color = GREEN
                    else:
                        energy_color = RED
                    pygame.draw.line(screen, energy_color, (plane.rect.left, plane.rect.top - 5),
                                     (plane.rect.left + int(plane.rect.width * energy_remain), plane.rect.top - 5), 2)

                else:  # 被摧毁
                    if not (delaySwitchImage % 3):
                        if enemy2_destroy_index == 0:
                            enemy2_down_sound.play()
                        screen.blit(plane.destroyImages[enemy2_destroy_index], plane.rect)
                        enemy2_destroy_index = (enemy2_destroy_index + 1) % 4
                        if enemy2_destroy_index == 0:
                            # 一辆中型敌机1000分
                            score += 3000
                            plane.reset()

            # 绘制小型敌方飞机
            for plane in smallEnemyPlanes:
                if plane.active:
                    plane.move()
                    screen.blit(plane.image, plane.rect)
                else:  # 被摧毁
                    if not (delaySwitchImage % 3):
                        if enemy1_destroy_index == 0:
                            enemy1_down_sound.play()
                        screen.blit(plane.destroyImages[enemy1_destroy_index], plane.rect)
                        enemy1_destroy_index = (enemy1_destroy_index + 1) % 4
                        if enemy1_destroy_index == 0:
                            # 一辆小型敌机100分
                            score += 500
                            plane.reset()

            # 绘制全屏炸弹数量
            bomb_text = bomb_font.render("x %d" % bomb_num, True, WHITE)
            text_rect = bomb_text.get_rect()
            screen.blit(bomb_image, (10, height - 10 - text_rect.height))
            screen.blit(bomb_text, (20 + bomb_rect.width, height - 5 - text_rect.height))
            # 绘制子弹数
            bullet_text = score_font.render("bullet num : %d" % len(really_bullets), True, WHITE)
            screen.blit(bullet_text, (0, 40))

            # 绘制生命数量
            if isNotDead:
                screen.blit(life_image, (width - life_rect.width, height - life_rect.height))
                # 绘制生命剩余数量
                life_text = score_font.render("Infinite x ", True, WHITE)
                screen.blit(life_text, (width - 3 * life_rect.width, height - 40))
            elif life_num:
                screen.blit(life_image, (width - life_rect.width, height - life_rect.height))
                # 绘制生命剩余数量
                life_text = score_font.render("%d x " % life_num, True, WHITE)
                screen.blit(life_text, (width - life_rect.width - 40, height - 40))

            # 绘制分数
            score_text = score_font.render("Score : %s" % str(score), True, WHITE)
            screen.blit(score_text, (10, 5))
        # 绘制游戏结束画面
        elif life_num == 0:

            # 之所以是暂停，因为我们可以使用外挂继续游戏
            # 暂停背景音乐
            pygame.mixer.music.stop()
            # 暂停全部音效
            pygame.mixer.stop()

            if not recorded:

                # 读取历史最高得分
                with open(projectPath + "/resources/record.txt", "r") as file:
                    record_score = int(file.read())
                # 如果得分大于历史最高分，则存档
                if score > record_score:
                    with open(projectPath + "/resources/record.txt", "w") as file:
                        file.write(str(score))

                recorded = True

            # 绘制结束界面
            record_score_text = score_font.render("Best : %d" % record_score, True, (255, 255, 255))
            screen.blit(record_score_text, (50, 50))

            gameover_text1 = gameover_font.render("Your Score", True, (255, 255, 255))
            gameover_text1_rect = gameover_text1.get_rect()
            gameover_text1_rect.left, gameover_text1_rect.top = \
                (width - gameover_text1_rect.width) // 2, height // 3
            screen.blit(gameover_text1, gameover_text1_rect)

            gameover_text2 = gameover_font.render(str(score), True, (255, 255, 255))
            gameover_text2_rect = gameover_text2.get_rect()
            gameover_text2_rect.left, gameover_text2_rect.top = \
                (width - gameover_text2_rect.width) // 2, \
                gameover_text1_rect.bottom + 10
            screen.blit(gameover_text2, gameover_text2_rect)

            again_rect.left, again_rect.top = \
                (width - again_rect.width) // 2, \
                gameover_text2_rect.bottom + 50
            screen.blit(again_image, again_rect)

            gameover_rect.left, gameover_rect.top = \
                (width - again_rect.width) // 2, \
                again_rect.bottom + 10
            screen.blit(gameover_image, gameover_rect)

            # 检测用户的鼠标操作
            # 如果用户按下鼠标左键
            if pygame.mouse.get_pressed()[0]:
                # 获取鼠标坐标
                pos = pygame.mouse.get_pos()
                # 如果用户点击“重新开始”
                if again_rect.left < pos[0] < again_rect.right and \
                        again_rect.top < pos[1] < again_rect.bottom:
                    # 调用main函数，重新开始游戏
                    main()
                # 如果用户点击“结束游戏”
                elif gameover_rect.left < pos[0] < gameover_rect.right and \
                        gameover_rect.top < pos[1] < gameover_rect.bottom:
                    # 退出游戏
                    pygame.quit()
                    sys.exit()

        # 绘制暂停按钮
        screen.blit(paused_image, paused_rect)
        pygame.display.flip()

        clock.tick(60)


if __name__ == '__main__':
    try:
        main()
    except SystemExit:
        pass
    except:
        traceback.print_exc()
        pygame.quit()
        input()
